package archer.framework.core;

import jodd.json.JoddJson;
import jodd.json.JsonContext;
import jodd.json.TypeJsonSerializer;
import jodd.typeconverter.TypeConverter;
import jodd.typeconverter.TypeConverterManager;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @author christ
 * @date 2016/3/31
 */
public class ArcherCoreModule {

    /**
     * 数据库中表示true的字段，默认为Y
     */
    public static String databaseBooleanTrue = "Y";

    /**
     * 数据库中表示false的字段，默认为N
     */
    public static String databaseBooleanFalse = "N";

    /**
     * 手机号验证规则配置
     */
    public static Pattern mobilePattern = Pattern.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$",
            Pattern.CASE_INSENSITIVE);


    /**
     * 自定义jodd配置
     */
    public static void initJoddConfig() {

        //java.util.Date按照yyyy-MM-dd格式处理
        JoddJson.defaultSerializers.register(Date.class, new TypeJsonSerializer() {

            @Override
            public boolean serialize(JsonContext jsonContext, Object value) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                jsonContext.writeString(dateFormat.format(value));
                return true;
            }
        });

        //java.sql.Date按照yyyy-MM-dd HH:mm:ss格式处理
        JoddJson.defaultSerializers.register(java.sql.Date.class, new TypeJsonSerializer() {

            @Override
            public boolean serialize(JsonContext jsonContext, Object value) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                jsonContext.writeString(dateFormat.format(value));
                return true;
            }
        });

        //java.sql.Timestamp按照yyyy-MM-dd HH:mm:ss格式处理
        JoddJson.defaultSerializers.register(Timestamp.class, new TypeJsonSerializer() {

            @Override
            public boolean serialize(JsonContext jsonContext, Object value) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                jsonContext.writeString(dateFormat.format(value));
                return true;
            }
        });

        JoddJson.defaultSerializers.register(UUID.class, new TypeJsonSerializer() {

            @Override
            public boolean serialize(JsonContext jsonContext, Object value) {
                jsonContext.writeString(value.toString());
                return true;
            }
        });

        //注册反序列化时UUID的解析
        TypeConverterManager.register(UUID.class, new TypeConverter() {

            @Override
            public Object convert(Object value) {
                return UUID.fromString(value.toString());
            }
        });

    }
}
